package Concurrency4_GeekTime.Chapter23_Future;

import java.util.concurrent.*;

/**
 * 功能说明：
 * 开发人员：@author MaLi
 */
public class Example2 {
    // 向电商S1询价，并保存
    // r1 = getPriceByS1();
    // save(r1);
    // 向电商S2询价，并保存
    // r2 = getPriceByS2();
    // save(r2);
    // 向电商S3询价，并保存
    // r3 = getPriceByS3();
    // save(r3);
    public static void main(String[] args) {
        //serialExecute();
        //优化
        //开启三个线程同时去做, 每个完成执行保存
        currentExecute();
    }

    private static void currentExecute() {
        ExecutorService service = Executors.newFixedThreadPool(6);
        long start = System.currentTimeMillis();
        Future<?> f1 = service.submit(() -> {
            float priceByS1 = getPriceByS1();//有问题, 网络IO, 不是马上返回
            save(priceByS1);
        });
        Future<?> f2 = service.submit(()->{
            float priceByS2 = getPriceByS2();
            save(priceByS2);
        });
        Future<?> f3 = service.submit(()->{
            float priceByS3 = getPriceByS3();
            save(priceByS3);
        });

        try {
            f1.get();
            f2.get();
            f3.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        long end = System.currentTimeMillis();
        System.out.println("优化后的时间消耗: "+(end-start));
        //service.shutdownNow();
    }

    private static void serialExecute() {
        long start = System.currentTimeMillis();
        //未添加任何优化的前提下:
        float r1 = getPriceByS1();
        save(r1);
        float r2 = getPriceByS2();
        save(r2);
        float r3 = getPriceByS3();
        save(r3);
        long end = System.currentTimeMillis();
        System.out.println("未经优化的时间消耗: "+(end-start));
    }


    public static float getPriceByS1() {
        System.out.println("getPriceByS1...");
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("获取到S1价格");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public static float getPriceByS2() {
        System.out.println("getPriceByS2...");
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("获取到S2价格");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 2;
    }

    public static float getPriceByS3() {
        System.out.println("getPriceByS3...");
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("获取到S3价格");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return 3;
    }

    public static void save(float price) {
        System.out.println("save..."+price);
        try {
            TimeUnit.SECONDS.sleep(2);
            System.out.println("结果已经保存");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
